package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.exceptions.InvalidFeed;
import com.acme.bankapp.domain.bank.*;

public class BankDataLoaderService {

	public static Client getClientFromFeedString(String token)
			throws InvalidFeed {
		Double balance = null, overdraft = null;
		char accountType = 0;
		Gender gender = null;
		String name = null;
		for (String field : token.split(";")) {
			String[] fieldParsed = field.split("=");
			if (fieldParsed.length != 2) {
				throw new InvalidFeed();
			}
			if (fieldParsed[0].equals("accounttype")) {
				accountType = fieldParsed[1].charAt(0);
			} else if (fieldParsed[0].equals("balance")) {
				balance = Double.parseDouble(fieldParsed[1]);
			} else if (fieldParsed[0].equals("overdraft")) {
				overdraft = Double.parseDouble(fieldParsed[1]);
			} else if (fieldParsed[0].equals("gender")) {
				gender = (fieldParsed[1].equals("m") ? Gender.MALE
						: Gender.FEMALE);
			} else if (fieldParsed[0].equals("name")) {
				name = fieldParsed[1];
			} else {
				throw new InvalidFeed();
			}
		}
		Account account;
		if ((name == null) || (gender == null)) {
			throw new InvalidFeed();
		}
		if (accountType == 'c') {
			if ((balance == null) || (overdraft == null)) {
				throw new InvalidFeed();
			}
			account = new CheckingAccount(balance, overdraft);
		} else if (accountType == 's') {
			if (balance == null) {
				throw new InvalidFeed();
			}
			account = new SavingsAccount(balance);
		} else {
			throw new InvalidFeed();
		}
		Client client = new Client(name, gender);
		client.setAccount(account);
		return client;
	}

	public static Bank loadFeed(File file) throws FileNotFoundException,
			InvalidFeed {
		Scanner input = new Scanner(file);
		try {
			Bank bank = new Bank();
			input.useDelimiter("\n");
			while (input.hasNext()) {
				String token = input.next();
				bank.addClient(getClientFromFeedString(token));
			}
			return bank;
		} finally {
			input.close();
		}
	}

}
